const Koa = require("koa");
const Router = require("koa-router");
const cors = require("koa2-cors");
const { koaBody } = require("koa-body");
const app = new Koa();
const router = new Router();
const serve = require("koa-static");

const user = require("./router/user");
const chat = require("./router/chat");
const env = require("./utils/env");

// 有关socket
const socket = require("./socket");

const httpServer = require("http").createServer(app.callback());
const options = {
  cors: {
    origin: ["http://127.0.0.1:3000"],
    credentials: true,
  },
};
const io = require("socket.io")(httpServer, options);

socket(io);

require("./database/index");
const errorHandler = require("./middleware/errorHandler");

env === "dev" && app.use(cors());
// 处理json  formdata等格式
app.use(koaBody());

app.use(async (ctx, next) => {
  console.log("全局中间件");
  await next();
});

app.use(user.routes());
app.use(chat.routes());

app.use(router.routes());
app.use(router.allowedMethods());
app.use(serve("../frontend/build"));
app.on("error", errorHandler);
// 服务开启在3020端口
httpServer.listen(3020, () => {
  console.log("服务开启成功", "127.0.0.1:3020");
});
